package com.home766.controller.admin;

import com.home766.dto.DictionaryDTO;
import com.home766.dto.SchemeProductDto;
import com.home766.entity.Dictionary;
import com.home766.entity.SchemeProduct;
import com.home766.service.IDictionaryService;
import com.home766.service.SchemeProductService;
import com.home766.util.StringUtil;
import net.biz.Message;
import net.biz.Page;
import net.biz.Pageable;
import net.biz.controller.admin.BaseController;
import net.biz.entity.Brand;
import net.biz.entity.Specification;
import net.biz.entity.SpecificationValue;
import net.biz.service.*;
import net.biz.util.ParamsUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.util.List;

/**
 * 方案产品-controller
 */
@Controller
@RequestMapping("/admin/scheme_product")
public class SchemeProductController extends BaseController {
	
	@Resource(name="schemeProductServiceImpl")
	private SchemeProductService schemeProductService;
	@Resource(name = "brandServiceImpl")
	private BrandService brandService;
	@Resource(name = "specificationServiceImpl")
	private SpecificationService specificationService;
	@Resource(name="specificationValueServiceImpl")
	private SpecificationValueService specificationValueService;
	@Resource(name="adminServiceImpl")
	private AdminService adminService;
	@Resource(name="snServiceImpl")
	private SnService snService;
	@Autowired
	private IDictionaryService iDictionaryService;
	
	
	/**
	 * 检查名称是否存在
	 * @param name
	 * @return
	 */
	@RequestMapping(value="/check_exist",method =RequestMethod.GET)
	@ResponseBody
	public boolean checkExists(String name){
		if (StringUtils.isEmpty(name)) {
			return false;
		}
		if (schemeProductService.checkExists(name)) {
			return false;
		} else {
			return true;
		}
	}
	
	/**
	 * 方案产品列表查询
	 * @param model
	 * @param pageable
	 * @return
	 */
	@RequestMapping(value="/list",method = RequestMethod.GET)
	public String list(ModelMap model, Pageable pageable){
		Page<SchemeProductDto> page = schemeProductService.findPage(pageable,null,null,null,null,null,null,null);
		model.addAttribute("page", page);
		//所有方案类型查询
		List<DictionaryDTO> types = iDictionaryService.searchChildren(ParamsUtil.SCHEME_TYPE);
		model.addAttribute("types", types);
		//所有品牌查询
		model.addAttribute("brands", brandService.findAll());
		return "/admin/scheme_product/list";
	}
	
	/**
	 * 新增
	 * @param model
	 * @return
	 */
	@RequestMapping(value="/add",method = RequestMethod.GET)
	public String add(ModelMap model){
		List<DictionaryDTO> types = iDictionaryService.searchChildren(ParamsUtil.SCHEME_TYPE);
		model.addAttribute("types", types);
		model.addAttribute("brands", brandService.findAll());
		model.addAttribute("specifications", specificationService.findAll());
		return "/admin/scheme_product/add";
	}
	
	/**
	 * 编辑
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/edit",method = RequestMethod.GET)
	public String edit(ModelMap model, Long id){
		SchemeProduct sp = schemeProductService.find(id);
		if(id == null || sp == null){
			return ERROR_VIEW;
		}
		model.addAttribute("schemeProduct", sp);
		model.addAttribute("brands", brandService.findAll());
		model.addAttribute("specifications", specificationService.findAll());
		List<DictionaryDTO> types = iDictionaryService.searchChildren(ParamsUtil.SCHEME_TYPE);
		List<DictionaryDTO> categorys = iDictionaryService.searchChildren(sp.getType());
		List<DictionaryDTO> schemeProducts = iDictionaryService.searchChildren(sp.getCategoryId());
		model.addAttribute("types", types);
		model.addAttribute("schemeProducts", schemeProducts);
		model.addAttribute("categorys", categorys);
		return "/admin/scheme_product/edit";
	}
	
	/**
	 * 详情
	 * @param model
	 * @param id
	 * @return
	 */
	@RequestMapping(value="/detail",method = RequestMethod.GET)
	public String detail(ModelMap model, Long id){
		SchemeProduct sp = schemeProductService.find(id);
		if(id == null || sp == null){
			return ERROR_VIEW;
		}
		List<DictionaryDTO> types = iDictionaryService.searchChildren(ParamsUtil.SCHEME_TYPE);
		List<DictionaryDTO> categorys = iDictionaryService.searchChildren(sp.getType());
		model.addAttribute("types", types);
		model.addAttribute("categorys", categorys);
		model.addAttribute("schemeProduct", sp);
		model.addAttribute("brands", brandService.findAll());
		model.addAttribute("specifications", specificationService.findAll());
		return "/admin/scheme_product/detail";
	}
	
	/**
	 * 保存
	 * @param sp
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value="/save",method = RequestMethod.POST)
	public String save(Long nameId, String name, Long type, Long brand,
                       Long category, Long specificationIds, BigDecimal price,Integer heatValue,Integer sortWeight,
                       String image, RedirectAttributes redirectAttributes, Boolean isTehui, Boolean isReward,
                       HttpServletRequest request) {
		if(nameId == null || type == null || brand == null || specificationIds == null ||
				price == null || heatValue == null ||sortWeight==null  || image == null){
			return ERROR_VIEW;
		}
		Brand b = brandService.find(brand);
		Specification spec = specificationService.find(specificationIds);
		String[] specificationValueIds = request.getParameterValues("specification_" + specificationIds);
		Dictionary dicName = iDictionaryService.find(nameId);
		Dictionary cate = iDictionaryService.find(category);
		
		if(b == null || spec == null || dicName == null || cate == null || specificationValueIds.length < 2){
			return ERROR_VIEW;
		}
		try {
			SchemeProduct sproduct = new SchemeProduct();
			sproduct.setCreatePerson(adminService.getCurrentUsername());
			sproduct.setName(dicName.getTitle());
			sproduct.setNameId(nameId);
			sproduct.setType(type);
			sproduct.setIsDelete(false);
			sproduct.setBrand(b);
			sproduct.setSpecification(spec);
			sproduct.setCategory(cate);
			sproduct.setCategoryId(category);
			sproduct.setPrice(price);
			sproduct.setHeatValue(heatValue);
			sproduct.setSortWeight(sortWeight);
			sproduct.setImage(image);
			isTehui = isTehui==null?false:true;
			sproduct.setIsTehui(isTehui);
			isReward = isReward==null?false:true;
			sproduct.setIsReward(isReward);
			List<DictionaryDTO> coefficients = iDictionaryService.searchChildren(nameId);
			if(coefficients != null && coefficients.size() > 0){
				try {
					double dou = Double.parseDouble(coefficients.get(0).getTitle());
					sproduct.setCoefficient(dou);
					sproduct.setDistType(ParamsUtil.SCHEME_PRODUCT_DIST_TYPE_HASCOE);
				} catch (Exception e) {
					e.printStackTrace();
					sproduct.setDistType(ParamsUtil.SCHEME_PRODUCT_DIST_TYPE_NOCOE);
					sproduct.setCoefficient(null);
				}
			}else{
				sproduct.setCoefficient(null);				
				if(!StringUtil.isNullOrSpace(dicName.getTitle())){
					if(ParamsUtil.SCHEME_PRODUCT_CUST_STR.contains(dicName.getTitle())){
						sproduct.setDistType(ParamsUtil.SCHEME_PRODUCT_DIST_TYPE_CUST);
					}else{
						sproduct.setDistType(ParamsUtil.SCHEME_PRODUCT_DIST_TYPE_NOCOE);
					}
				}
			}
			//保存方案产品操作
			boolean issuccess = schemeProductService.saveSchemeProducts(sproduct,specificationValueIds);
			if(issuccess){
				addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
				return "redirect:list.jhtml";
			}else{
				addFlashMessage(redirectAttributes, ERROR_MESSAGE);
				return "redirect:add.jhtml";				
			}
		} catch (Exception e) {
			e.printStackTrace();
			addFlashMessage(redirectAttributes, ERROR_MESSAGE);
			return ERROR_VIEW;
		}
	}
	
	/**
	 * 更新
	 * @param sp
	 * @param redirectAttributes
	 * @return
	 */
	@RequestMapping(value="/update",method = RequestMethod.POST)
	public String update(Long id, Long nameId, String name, Long type,
                         Long brand, Long category, Long specificationIds, BigDecimal price,Integer heatValue,Integer sortWeight,
                         String image, RedirectAttributes redirectAttributes, Boolean isTehui, Boolean isReward,
                         HttpServletRequest request) {
		if(nameId == null || type == null || brand == null || specificationIds == null ||
				price == null || heatValue == null ||sortWeight==null  || image == null){
			return ERROR_VIEW;
		}
		SchemeProduct sproduct = schemeProductService.find(id);
		if(sproduct == null){
			return ERROR_VIEW;
		}
		Brand b = brandService.find(brand);
		Specification spec = specificationService.find(specificationIds);
		String[] specificationValueIds = request.getParameterValues("specification_" + specificationIds);
		Dictionary dicName = iDictionaryService.find(nameId);
		Dictionary cate = iDictionaryService.find(category);
		if(b == null || spec == null || cate == null || dicName == null || specificationValueIds.length < 1){
			return ERROR_VIEW;
		}
		try {
			Long specificationValueId = Long.parseLong(specificationValueIds[specificationValueIds.length - 1]);
			SpecificationValue specVal = specificationValueService.find(specificationValueId);
			if(specVal == null){
				return ERROR_VIEW;
			}
			sproduct.setNameId(nameId);
			sproduct.setName(dicName.getTitle());
			sproduct.setType(type);
			sproduct.setBrand(b);
			sproduct.setSpecification(spec);
			sproduct.setSpecificationValue(specVal);
			sproduct.setPrice(price);
			sproduct.setHeatValue(heatValue);
			sproduct.setSortWeight(sortWeight);
			sproduct.setImage(image);
			sproduct.setCategory(cate);
			sproduct.setCategoryId(category);
			isTehui = isTehui==null?false:true;
			sproduct.setIsTehui(isTehui);
			isReward = isReward==null?false:true;
			sproduct.setIsReward(isReward);
			List<DictionaryDTO> coefficients = iDictionaryService.searchChildren(nameId);
			if(coefficients != null && coefficients.size() > 0){
				try {
					double dou = Double.parseDouble(coefficients.get(0).getTitle());
					sproduct.setCoefficient(dou);
					sproduct.setDistType(ParamsUtil.SCHEME_PRODUCT_DIST_TYPE_HASCOE);
				} catch (Exception e) {
					e.printStackTrace();
					sproduct.setCoefficient(null);
					sproduct.setDistType(ParamsUtil.SCHEME_PRODUCT_DIST_TYPE_NOCOE);
				}
			}else{
				sproduct.setCoefficient(null);
				if(!StringUtil.isNullOrSpace(dicName.getTitle())){
					if(ParamsUtil.SCHEME_PRODUCT_CUST_STR.contains(dicName.getTitle())){
						sproduct.setDistType(ParamsUtil.SCHEME_PRODUCT_DIST_TYPE_CUST);
					}else{
						sproduct.setDistType(ParamsUtil.SCHEME_PRODUCT_DIST_TYPE_NOCOE);
					}
				}
			}
			//保存方案产品操作
			schemeProductService.update(sproduct);
			addFlashMessage(redirectAttributes, SUCCESS_MESSAGE);
			return "redirect:list.jhtml";
		} catch (Exception e) {
			e.printStackTrace();
			addFlashMessage(redirectAttributes, ERROR_MESSAGE);
			return ERROR_VIEW;
		}
	}
	
	/**
	 * 删除
	 * @param model
	 * @param ids
	 * @return
	 */
	@RequestMapping(value="/delete",method = RequestMethod.POST)
	@ResponseBody
	public Message delete(ModelMap model, Long[] ids){
		if(ids == null || ids.length == 0){
			return ERROR_MESSAGE;
		}
		try {
			schemeProductService.delete(ids);
			return SUCCESS_MESSAGE;
		} catch (Exception e) {
			e.printStackTrace();
			return ERROR_MESSAGE;
		}
	}
	
	/**
	 * 根据类型查询分类
	 * @param type
	 * @return
	 */
	@RequestMapping(value="/findSchemeProductCategory",method = RequestMethod.POST)
	@ResponseBody
	public List<DictionaryDTO> findSchemeProductCategory(Long type){
		if(type ==  null){
			return null;
		}
		return iDictionaryService.searchChildren(type);
	}
	
	/**
	 * 根据分类查询名称
	 * @param type
	 * @return
	 */
	@RequestMapping(value="/findSchemeProduct",method = RequestMethod.POST)
	@ResponseBody
	public List<DictionaryDTO> findSchemeProduct(Long category){
		if(category ==  null){
			return null;
		}
		return iDictionaryService.searchChildren(category);
	}
	
}
